package com.dahaiwuliang.code.controller.admin;

import com.dahaiwuliang.code.lucene.ArticleIndex;
import com.dahaiwuliang.code.pojo.Article;
import com.dahaiwuliang.code.pojo.Message;
import com.dahaiwuliang.code.pojo.User;
import com.dahaiwuliang.code.server.ArticleService;
import com.dahaiwuliang.code.server.CommentService;
import com.dahaiwuliang.code.server.LinkService;
import com.dahaiwuliang.code.server.MessageService;
import com.dahaiwuliang.code.util.StringUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author bzd
 */
@RestController
@RequestMapping(value = "/admin/article")
public class ArticleAdminController {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private ArticleIndex articleIndex;

    @Autowired
    private  CommentService commentService;
    @Autowired
    private MessageService messageService;

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    /**
     *
     * @param s_article 条件
     * @param nickname 昵称
     * @param publishDates 发布时间
     * @param page 当前页
     * @param pageSize 每页肌肉数
     * @return
     */
    @RequestMapping(value = "/list")
    @RequiresPermissions(value = "分页查询资源信息列表")
    public Map<String,Object> list(Article s_article,
                                    @RequestParam(value = "nickname",required = false) String nickname,
                                    @RequestParam(value = "publishDates",required = false) String publishDates,
                                    @RequestParam(value = "page",required = false) Integer page,
                                    @RequestParam(value = "pageSize",required = false) Integer pageSize){
        Map<String,Object> resultMap=new HashMap<>();
        String s_bpublishDate = null;       //开始时间
        String s_epublishDate = null;       //结束时间
        if (StringUtil.isNotEmpty(publishDates)){
            String[] str = publishDates.split(" - ");       //拆分时间段
            s_bpublishDate = str[0];
            s_epublishDate = str[1];
        }
        resultMap.put("data",articleService.list(s_article,nickname,s_bpublishDate,s_epublishDate,page,pageSize, Sort.Direction.DESC,"publishDate"));
        resultMap.put("total",articleService.getCount(s_article,nickname,s_bpublishDate,s_epublishDate));
        resultMap.put("errorNo",0);
        return resultMap;
    }
    /**
     * 批量删除资源
     */
    @RequestMapping(value = "/delete")
    @RequiresPermissions(value = "删除资源")
    public Map<String,Object> delete(@RequestParam(value = "articleId")String ids){
        Map<String,Object> resultMap=new HashMap<>();
        String[] idsStr=ids.split(",");
        for (int i=0;i<idsStr.length;i++){
            commentService.deleteByArticleId(Integer.parseInt(idsStr[i]));
            articleService.delete(Integer.parseInt(idsStr[i]));
            articleIndex.deleteIndex(idsStr[i]);
        }
   resultMap.put("errorNo",0);
        return resultMap;
    }
    /**
     * 查看或审核资源页面所需要的数据
     */
    @RequestMapping("/findById")
    @RequiresPermissions(value = "修改资源")
    public Map<String,Object> toModifyArticlePage(Integer articleId){
        Article article=articleService.getById(articleId);
        Map<String,Object> resultMap = new HashMap<>();
        Map<String,Object> tempMap = new HashMap<>();
        tempMap.put("articleId",article.getArticleId());
        tempMap.put("name",article.getName());
        tempMap.put("arcType",article.getArcType().getArcTypeId());
        tempMap.put("points",article.getPoints());
        tempMap.put("content",article.getContent());
        tempMap.put("download",article.getDownload());
        tempMap.put("password",article.getPassword());
        tempMap.put("click",article.getClick());
        tempMap.put("keywords",article.getKeywords());
        tempMap.put("description",article.getDescription());

        resultMap.put("data",tempMap);
        resultMap.put("errorNo",0);
        return  resultMap;
    }
    /**
     * 审核资源
     */
    @RequestMapping("/updateState")
    @RequiresPermissions(value = "审核资源")
    public Map<String,Object> updateState(Article article){
        Article Oldarticle1=articleService.getById(article.getArticleId());
        Map<String,Object> resultMap = new HashMap<>();
        Message message=new Message();
        message.setUser(Oldarticle1.getUser());
        message.setPublishDate(new Date());
        Oldarticle1.setCheckDate(new Date());
        if (article.getState()==2){
            message.setContent("【<font color='#00ff7f' >审核成功</font>】您发布的【"+Oldarticle1.getName()+"】审核成功");
            Oldarticle1.setState(2);
        }else if (article.getState()==3){
            message.setContent("【<font color='#00ff7f >审核失败</font>】您发布的【"+Oldarticle1.getName()+"】审核失败");
            message.setCause(Oldarticle1.getReason());
            Oldarticle1.setState(3);
            Oldarticle1.setReason(article.getReason());
        }
messageService.save(message);
        articleService.save(Oldarticle1);
        if (Oldarticle1.getState()==2){
            articleIndex.addIndex(Oldarticle1);
            redisTemplate.opsForList().rightPush("allarticleId",Oldarticle1.getArticleId());
            redisTemplate.opsForList().rightPush("article_type_"+Oldarticle1.getArcType().getArcTypeId(),Oldarticle1.getArticleId());
        }
        resultMap.put("errorNo",0);
        return resultMap;
    }
    /**
     * 生成所有资源帖子索引
     */
    @ResponseBody
    @RequestMapping(value = "/genAllIndex")
    @RequiresPermissions(value = "生成所有资源帖子索引")
    public  boolean genAllIndex(){
        List<Article> articleList=articleService.listStatePass();
       if (articleList==null||articleList.size()==0){
           return  false;
       }
       for (Article article:articleList){
           try {

           article.setContentNoTag(StringUtil.stripHtml(article.getContent()));
        articleIndex.addIndex(article);
       }catch (Exception e){
               e.printStackTrace();
               return  false;
           }
       }

        return true;
    }
    @RequestMapping(value = "/updateHotState")
    @RequiresPermissions (value = "是否热门资源")
    public Map<String,Object>  updateHotState( @RequestParam(value = "articleId")Integer articleId,boolean isHot ){
        Article oldarticle=articleService.getById(articleId);
        oldarticle.setHot(isHot);
        articleService.save(oldarticle);
        Map<String,Object> resultMap=new HashMap<>();


     ;
        resultMap.put("success",true);
        return  resultMap;}

    @RequestMapping(value = "/updateFreeState")
    @RequiresPermissions (value = "是否免费资源")
    public Map<String,Object>  updateFreeState( Integer articleId,boolean isFree ){
        Article oldarticle=articleService.getById(articleId);
        oldarticle.setFree(isFree);

        articleService.save(oldarticle);
        Map<String,Object> resultMap=new HashMap<>();



        resultMap.put("success",true);
        return  resultMap;}
}
